/*
Class Name      : ConfirmAndCloseCaseForWCM
Created by      : Suneetha Allam Venkata
Created On      : 06/02/2013
Description     : This class helps to release the all cases of a perticular account of an WCM who is working on the cases.
                  Before closing the cases it will verify whether the all manditatory fields have values or not. If they dont have any values , simply we displaythe error messages   
Version         : 1.0         
*/
/*
Modified By     : Suneetha Allam Venkata
Version         : 1.0 
Description     : Query  Changed 
     Condisering  Account & lead and 
     User realted cases  by checking  Last_Contacted_Advisor, Ownerid
*/
public without sharing class  ConfirmAndCloseCaseForWCM
{   
    
    //Cases list
   list<Case> CasesToDisplayOnVFpageList; //Case list to close
     
    public String UserProfileName;
    public boolean showTable{get;set;}
    boolean isSuccess;
    public id AccId;
    public id  leadId;
    DateTIme PageLoadedTime;
    Set<Id> QueueIdsList;
     Set<Id> NONQueueIdsList;
     
     
    //=====================================//
    // String variables to find out errors //
    //=====================================//
    public String ErrMsgForNotesStr;
    public String ErrMsgForNonClosedCaseNextCallTimeStr;
    public String ErrMsgForNonClosedCaseInCorrectNextCallTimeStr;
    public String ErrMsgForStatuStr;
    
    
    
    //===============================================================//
    //========================== Constroctor=========================//
    // Helps to get the list of non closed cases and cases which are //
    // assigned to logged in WEST Support associated to perticular account.   // 
    //===============================================================//
     public ConfirmAndCloseCaseForWCM()
    {
       try
       { 
            showTable=false;
            CasesToDisplayOnVFpageList = new list<Case>();
            
            //Parameters
            system.debug('Case Close Id===>'+ApexPages.currentPage().getParameters().get('accId'));
            system.debug('Case Close Id===>'+ApexPages.currentPage().getParameters().get('leadid'));
            String strAccountId = ApexPages.currentPage().getParameters().get('accId');
            String strLeadId = ApexPages.currentPage().getParameters().get('leadid');
            if(strAccountId != null && strAccountId != '')
                aCcId = ApexPages.currentPage().getParameters().get('accId');
            if(strLeadId != null && strLeadId != '')
                leadId = ApexPages.currentPage().getParameters().get('leadid');
                
            //Initial loading
            init();
            
            // UserProfileName=[select name from profile where id=:UserInfo.getProfileId() limit 1].name;
       }
       Catch(Exception e)
        {
            //errMessage('Exception+ ConfirmAndCloseCaseForWCMTest =====>'+e);
           // GeneralUtilWCM.saveLog( e.getMessage(), ' ConfirmAndCloseCaseForWCMTest',' ConfirmAndCloseCaseForWCMTest');
        }
    }

    //===============================================================//
    //========================== doRefresh================================//
    // Helps to Refresh          //
    //===============================================================//
     public pageReference doRefresh()
      {
            CasesToDisplayOnVFpageList.clear();
            PageReference pr= new PageReference('/apex/ConfirmAndCloseCaseVF?accId='+accid);
            pr.setRedirect(true);
            return pr;
      }
    
     
    //===============================================================//
    //========================== init================================//
    //Helps Get the cases based  on  AccountId & RecordType is West and status not closed       //
    //===============================================================//
    public void init()
    {
        
       try
       {
            CasesToDisplayOnVFpageList = new list<Case>();
            NONQueueIdsList=GeneralUtilWCM.getNotADAODMQueueIdsList(); 
             QueueIdsList=GeneralUtilWCM.getQueueIdNotADAorODM();
             /*Added Case_Name__c to the query by Kalyani*/
            CasesToDisplayOnVFpageList=[Select id,CaseNumber,Case_Name__c, Subject,Status,Description,Notes__c,Next_Call__c 
                                        From Case  
                                        where ((Case.Account.id=:AccId and Case.Lead__c=:leadId)
                                                and recordtypeid =:GeneralUtilWCM.getRecordType()
                                                and Status!='Closed'
                                                and  (OwnerId=:UserInfo.getUserId()
                                                     or  OwnerId IN :QueueIdsList))
                                           Order by Createddate desc];
             PageLoadedTime=dateTime.now(); 
             if(CasesToDisplayOnVFpageList.size()>0)
                    showTable=true;
                    
                 }
       Catch(Exception e)
        {
            //errMessage('Exception+ ConfirmAndCloseCaseForWCMTest =====>'+e);
           // GeneralUtilWCM.saveLog( e.getMessage(), 'init',' ConfirmAndCloseCaseForWCMTest');
        }
    }
    
    
    
    //==============================================================//
    //===Error Function:Helps to diplay error messages on VF page ===//
    //==============================================================//
    public void errMessage(string  ErrMsgStr)
    {
        ApexPages.Message myErrMsg=new ApexPages.Message(ApexPages.Severity.ERROR, ErrMsgStr );
        ApexPages.AddMessage(myErrMsg); 
    }
    
    
    //==============================================================//
    //==========Helps to display list of cases  on VF page =========//
    //==============================================================//
    public List<Case> getCases() 
    {
        system.debug('*****************');
        system.debug('*****************'+CasesToDisplayOnVFpageList);
        return CasesToDisplayOnVFpageList; 
    }
    
  

       
   public PageReference ConfirmAndClose()
    {      
          //==============================================================/
          // If there are any non colsed cases assigned to the user then only he is able to close the
          //==============================================================/
          System.debug('Entered the confirm and close');
          
           if(showTable)  
            {
                Integer NumberOfCaseRecordsNeedsTobeClosedInt=0;
                
                NumberOfCaseRecordsNeedsTobeClosedInt=[Select count() 
                                                       from Case 
                                                       where ((Case.Account.id=:AccId and Case.Lead__c=:AccId)
                                                        and recordtypeid =:GeneralUtilWCM.getRecordType()
                                                        and Status!='Closed'
                                                        and  (OwnerId=:UserInfo.getUserId()
                                                        or  OwnerId IN :QueueIdsList)  
                                                        and    OwnerId Not IN:NONQueueIdsList )  and CreatedDate>=:PageLoadedTime];
                                                        
                                                        
                 //Checking  Is  any new records  exists                                          
                if(NumberOfCaseRecordsNeedsTobeClosedInt>0)
                {
                   
                    List<Case> recentlyCreatedCaseList=
                                     [Select id,CaseNumber,Subject,Status,Description,Notes__c,Next_Call__c 
                                       From Case where ((Case.Account.id=:AccId and Case.Lead__c=:AccId)
                                                    and recordtypeid =:GeneralUtilWCM.getRecordType()
                                                    and Status!='Closed'
                                                    and  (OwnerId=:UserInfo.getUserId()
                                                    or  OwnerId IN :QueueIdsList)
                                                    and    OwnerId Not IN:NONQueueIdsList ) ];
                                       
                    list<Case> TempCasesToHoldList=new list<Case>();
                    TempCasesToHoldList=CasesToDisplayOnVFpageList.clone();
                    
                    CasesToDisplayOnVFpageList.clear();
                    
                   
                    for(Case caseItr: recentlyCreatedCaseList)
                    {
                        CasesToDisplayOnVFpageList.add(caseItr);
                    }    
                    for(Case CaseToCloseItr :TempCasesToHoldList)
                    {
                        CasesToDisplayOnVFpageList.add(CaseToCloseItr);
                    }
                    PageLoadedTime=dateTime.now();          
                    errMessage('There are few more Cases to do confirm and close.Please work on them also');
                    return null;                           
                                        
                }
          
                ErrMsgForNotesStr='';
                ErrMsgForNonClosedCaseNextCallTimeStr='';
                ErrMsgForNonClosedCaseInCorrectNextCallTimeStr='';
                ErrMsgForStatuStr='';
                
                
                list<Case> CasesToUpdateOwner= new list<Case>();
                isSuccess=true;
                
                for(Case CaseIterator :CasesToDisplayOnVFpageList) // Helps to process each case whether they have any error condditions or not
                {  
                    //Added on 07/02/2013  updating Last contacted advisor  and Last contacted time
                    CaseIterator.Last_Contacted_Advisor_User__c= UserInfo.getUserId(); 
                    CaseIterator.Last_Contacted_Time__c=System.now();
                    CaseIterator.Manual_status_change__c=true;
                                            
                       //Modified by Sreekanth SV Vegi  on 15 feb 2013
                      CaseIterator.IsEscalated=false;
                      System.debug('Entry point to check the status' +CaseIterator.Status +'And the Iterator' +CaseIterator +'Also' +CaseIterator.Queue_Name__c);
                      if((CaseIterator.Status=='On Hold (Advisor)') || (CaseIterator.Status=='On Hold (Student)'))
                       {
                         CaseIterator.OwnerId = CaseIterator.Last_Contacted_Advisor_User__c;         
                       }
                       else if(CaseIterator.Status=='Transferred')
                       {
                                System.debug('This is the status ' +CaseIterator.Status +'and Queue is' +GeneralUtilWCMTest.getQueueIdforCase(CaseIterator));
                                 CaseIterator.OwnerId = GeneralUtilWCMTest.getQueueIdforCase(CaseIterator);
                       }
                       else if(CaseIterator.Status=='Escalated')
                       {
                          CaseIterator.OwnerId=GeneralUtilWCMTest.getQueueIdforEscalatedCase();
                            CaseIterator.IsEscalated=true;
                                
                       }
                     
                             
                     //modification ended by sreekanth   on 15 feb 2013
                     
                     
                         
                  
                    //---
                    
                      ///errMessage('..Case====>'+CaseIterator.Notes__c.length() +'st' + CaseIterator.Status);
                     ///errMessage('...isSuccess='+isSuccess);
                     //System.debug('CaseIterator.SelectedStatus====>'+CaseIterator.SelectedStatus);
                      //Validating Notes text
                      
                      if (CaseIterator.Status=='None')
                      {//added  by suneetha
                         
                                                    
                         ErrMsgForStatuStr = ErrMsgForStatuStr +CaseIterator.CaseNumber+', '; 
                        isSuccess=false;
                      }
                      
                      
                try
                {
                      if( CaseIterator.Notes__c==null )
                        {
                            ErrMsgForNotesStr =ErrMsgForNotesStr +CaseIterator.CaseNumber+', '; 
                            isSuccess=false;
                        }
                        
                             if(CaseIterator.Notes__c.length()==0)
                            {
                               ErrMsgForNotesStr =ErrMsgForNotesStr +CaseIterator.CaseNumber+', '; // Notes should not contain more than 5000 characters
                              isSuccess=false;
                            }
                            
                   }
                            
       catch(Exception e)
        {
           ErrMsgForNotesStr =ErrMsgForNotesStr +CaseIterator.CaseNumber+', '; // Notes should not contain more than 5000 characters
           isSuccess=false;
           system.debug('Exceptiion in Notes  ==:notes is'+ CaseIterator.Notes__c);   
           //  GeneralUtilWCM.saveLog( 'Sorry you don\'t have permissions to close the cases', ' ConfirmAndCloseCaseForWCMTest',' ConfirmAndCloseCaseForWCM');
        }   
                   //Validating Next call time  when  status  not closed          
                    if(CaseIterator.Status!='Closed')
                    {
                      
                       if(CaseIterator.Next_Call__c==null)
                        {
                            ErrMsgForNonClosedCaseNextCallTimeStr=ErrMsgForNonClosedCaseNextCallTimeStr+CaseIterator.CaseNumber+', '; // Please select the next call time for non closed cases
                            isSuccess=false;
                        }
                      if(CaseIterator.Next_Call__c<=system.now())
                        {
                            ErrMsgForNonClosedCaseInCorrectNextCallTimeStr=ErrMsgForNonClosedCaseInCorrectNextCallTimeStr+CaseIterator.CaseNumber+', ';
                              isSuccess=false;
                        }   
                    }
                    else
                    
                    { 
                        //    CaseIterator.IsClosed=true;
                          //  CaseIterator.ClosedDate=System.now();
                      }
                    
                     
                }  
                     

         if(isSuccess==false)
         {
                     if(ErrMsgForNotesStr!='')
                        errMessage('Please provide Notes for Case(s) '+ErrMsgForNotesStr.substring(0,ErrMsgForNotesStr.LastindexOf(',')) );
                    if(ErrMsgForNonClosedCaseInCorrectNextCallTimeStr!='')
                        errMessage('Next call time should be greater than Current date and time for Case(s) '+ErrMsgForNonClosedCaseInCorrectNextCallTimeStr.substring(0,ErrMsgForNonClosedCaseInCorrectNextCallTimeStr.LastindexOf(',')));
                    if(ErrMsgForNonClosedCaseNextCallTimeStr!='')
                        errMessage('Please provide Next Call Time for Case(s) '+ErrMsgForNonClosedCaseNextCallTimeStr.substring(0,ErrMsgForNonClosedCaseNextCallTimeStr.LastindexOf(',')));
                        if(ErrMsgForStatuStr!='')
                            errMessage('Please select status for Cses(s) ' + ErrMsgForStatuStr);
                    return null;     
         }
              try
                {
                    for(Case CaseIterator :CasesToDisplayOnVFpageList)
                    {
                     //  errMessage('Before update cases ===============>'+CaseIterator);
                    
                        CasesToUpdateOwner.add(CaseIterator);
                    }   
                    update CasesToUpdateOwner;
                    DeleteCaseTrackerRecordsAndCreateLog(CasesToUpdateOwner);
                    // errMessage('After update cases ===============>'+CasesToUpdateOwner);
               }
                Catch(Exception e)
                {
                    //errMessage('Exception =====>'+e);
                    //GeneralUtil_AC.saveApplicationLog(null, null,null, null, e.getMessage(), 'ConfirmAndCloseCaseForSSA_AC','','');
                }
                                                                      
          
                showTable=false;
                CasesToDisplayOnVFpageList.clear();
                system.debug('Page redirect to Case Page Close');
                PageReference pr= new PageReference('/apex/casepageclosevf');
                pr.setRedirect(true);
                return pr;
              
          }
         
      
      else
   {
           errMessage('Sorry you don\'t have permissions to close the cases');
         //   //GeneralUtilWCM.saveLog('Sorry you don\'t have permissions to close the cases', ' ConfirmAndClose',' ConfirmAndCloseCaseForWCM');
         //   PageReference pr= new PageReference('/apex/casepageclosevf');
        //        pr.setRedirect(true);
         //       return pr;
              
       }
            
        return null;           
    }
    public void DeleteCaseTrackerRecordsAndCreateLog(List<Case> KeyCasesList)
    {
        string tenantId;
        try
        {
              // errMessage('Tasks before insert===>');
            List<id> CaseIdToDeleteCaseTrackerList= new list<id>();
            List<Task> TasksToInsertForCases=new List<Task>();
            Task TaskObj=new Task();
            id ContactId=[Select c.Id From Contact c where c.AccountId=:AccId Limit 1].id;
            for(Case CaseObj:KeyCasesList)
            {
                CaseIdToDeleteCaseTrackerList.add(CaseObj.id);
               
                    TaskObj=new Task();
                    TaskObj.whatId = CaseObj.id;
                    TaskObj.whoId = ContactId;
                    TaskObj.Subject='Call';
                    TaskObj.Type = 'Phone';
                    TaskObj.Next_Call__c=CaseObj.Next_Call__c;
                    TaskObj.Status='Completed';
                    TaskObj.Priority='High';
                    TaskObj.Description=CaseObj.Notes__c;
                    system.debug('For testing purpose ======>'+userInfo.getUserId());
                    TaskObj.OwnerId=userInfo.getUserId();
                    system.debug('TaskObj ======>'+TaskObj);
                    TasksToInsertForCases.add(TaskObj);
                  }
       
            insert TasksToInsertForCases;
          
        }
        catch(Exception e)
        {
           //  errMessage('Exceptiion in task==:' + e.getMessage());
           //  system.debug('Exceptiion ==:'+e);   
           //  GeneralUtilWCM.saveLog( 'Sorry you don\'t have permissions to close the cases', ' ConfirmAndCloseCaseForWCMTest',' ConfirmAndCloseCaseForWCM');
        }   
    }
}